package com.example.demo.controller;

import com.alibaba.fastjson.JSONObject;
import com.example.demo.controller.dto.UserDTO;
import com.example.demo.entity.User;
import com.example.demo.service.UserService;
import com.example.demo.util.TokenUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@RestController
public class UserController {
    @Autowired
    UserService userService;

    /**
     * 保存用户
     * @param userDTO
     * @return
     */
    @RequestMapping("/register")
    public String register(@RequestBody(required = false) UserDTO userDTO){
        JSONObject json = new JSONObject();
        json.put("code","0");
        if(userDTO==null||userDTO.getPassword()==null||userDTO.getUsername()==null){
            json.put("msg","failed");
            return json.toString();
        }
        User user = new User();
        user.setUsername(userDTO.getUsername());
        user.setPassword(userDTO.getPassword());
        if(userService.userExists(user)!=null){
            json.put("msg","user exists");
            json.put("data",user);
            return json.toString();
        }
        userService.saveUser(user);
        json.put("code","1");
        json.put("msg","success");
        json.put("data",user);
        return json.toString();
    }

    /**
     * 实现用户登录
     * @param userDTO
     * @return
     */
    @RequestMapping(value="/login",method = {RequestMethod.GET,RequestMethod.POST})
    public String login(@RequestBody(required = false) UserDTO userDTO) {
        JSONObject json = new JSONObject();
        json.put("code","0");
        if (userDTO==null||userDTO.getPassword()==null||userDTO.getUsername()==null) {
            json.put("msg","username or password is empty");
            return json.toString();
        }
        User user = new User();
        user.setUsername(userDTO.getUsername());
        user.setPassword(userDTO.getPassword());
        if(userService.select(user)==null) {
            json.put("msg","username or password is wrong");
            return json.toString();
        }
        HttpSession session = ((ServletRequestAttributes) RequestContextHolder
                .getRequestAttributes()).getRequest().getSession();
        session.setAttribute("id",user.getId());
        session.setAttribute("username",user.getUsername());
        session.setAttribute("password",user.getPassword());
        String token = TokenUtil.generateToken(user);
        json.put("code","1");
        json.put("msg","success");
        json.put("data",user);
        json.put("token",token);
        return  json.toString();
    }
}


